package com.playball.lottery.frm.yhzx;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.JddMainActivity;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.ShowCustomDialog;
import com.playball.lottery.customview.ShowCustomDialog2;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.eventmanger.EventManager;
import com.playball.lottery.eventmanger.EventType;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.cache.MyPreference;


public class JddAlterPassActivity extends BaseActivity {

	TextView tv_title;
	private TextView btn_title_left;
	private Button btn_commit;
	private EditText et_userPassword;
	private EditText et_userConfirmPassword;
	private ShowTipDialog showdialog = new ShowTipDialog();
	private String username;
	private String mobile;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.jdd_alter_pass);
		Intent intent = getIntent();
		username = intent.getStringExtra("username");
		mobile = intent.getStringExtra("mobile");
		tv_title = (TextView) findViewById(R.id.top_title_info);
		btn_title_left = (TextView) findViewById(R.id.top_title_back);
		btn_commit = (Button) findViewById(R.id.btn_commit);
		et_userPassword = (EditText) findViewById(R.id.et_password);
		et_userConfirmPassword = (EditText) findViewById(R.id.et_confirm_password);

		tv_title.setText("修改密码");

		// 返回
		btn_title_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				GoBack();
			}
		});

		btn_commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					// close keyboard
					InputMethodManager inputmanger = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					inputmanger.hideSoftInputFromWindow(btn_commit.getWindowToken(), 0);
					if (et_userPassword.getText().toString().equals("")) {
						Toast.makeText(JddAlterPassActivity.this, R.string.password_cannot_be_empty, Toast.LENGTH_SHORT)
								.show();
					} else if (et_userConfirmPassword.getText().toString().equals("")) {
						Toast.makeText(JddAlterPassActivity.this, R.string.confirm_password_cannot_be_empty,
								Toast.LENGTH_SHORT).show();
					} else if (!et_userPassword.getText().toString()
							.equals(et_userConfirmPassword.getText().toString())) {
						Toast.makeText(JddAlterPassActivity.this, R.string.password_and_confirm_password_no_match,
								Toast.LENGTH_SHORT).show();
					} else if (et_userPassword.getText().toString().length() < 6
							| et_userPassword.getText().toString().length() > 15) {
						Toast.makeText(JddAlterPassActivity.this, R.string.enter_the_password_for_six_to_fifteen,
								Toast.LENGTH_SHORT).show();
					} else if (et_userPassword.getText().toString().length() != (et_userPassword.getText().toString()
							.replace(" ", "").length())) {
						Toast.makeText(JddAlterPassActivity.this, R.string.not_contain_spaces, Toast.LENGTH_SHORT)
								.show();
					} else {
						AsyncLoader task = new AsyncLoader();
						task.execute("1061");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	public void AlterPass() {
		ShowCustomDialog2 alertDialog = new ShowCustomDialog2.Builder(this).setTitle("温馨提示")
				.setMessage("密码修改成功，请重新登录天彩彩票").setNegativeButton("马上登录", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
						
						NextAsyncLoader task=new NextAsyncLoader();
						task.execute("101");
						
//						finish();
					}
				}).createCustomDialog();
		alertDialog.show();
	}

	public class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(JddAlterPassActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... params) {
			String strResult;
			try {
				JSONObject param = new JSONObject();
				param.put("username", username);
				param.put("mobile", mobile);
				param.put("newpwd", et_userPassword.getText().toString());
				String action = params[0];
				// 获取请求返回值
				strResult = GetRequestParams.getRequestResult(param.toString(), action, getApplicationContext());
				return strResult;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
				return null;
			}
		}

		// 完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {

					System.out.println("result = " + result);

					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {
						AlterPass();
					}
					Toast.makeText(JddAlterPassActivity.this, js.getString("Data"), Toast.LENGTH_SHORT).show();
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(JddAlterPassActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

	}

	// 返回
	public void GoBack() {
		ShowCustomDialog alertDialog = new ShowCustomDialog.Builder(this).setTitle("温馨提示").setMessage("您不打算设置新密码吗？")
				.setPositiveButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).setNegativeButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						JddAlterPassActivity.this.finish();

					}
				}).createCustomDialog();
		alertDialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			GoBack();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	};
	
	public class NextAsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask
		
		protected void onPreExecute() {
			showdialog.showDialog(JddAlterPassActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... params) {
			String strResult;
			try {

				// 设置请求所需参数
				JSONObject param = new JSONObject();
				param.put("Name", username);
				param.put("Pw", et_userConfirmPassword.getText().toString());// Password
				String action = params[0];
				// 获取请求返回值
				strResult = GetRequestParams.getRequestResult(param.toString(),
						action, JddAlterPassActivity.this.getApplicationContext());
				return strResult;
			} catch (Exception e) {
				// TODO: handle exception
				Log.e("error", e.toString());
				return null;
			}
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					// 接下来的就是JSON对象的操作了
					if (Integer.parseInt(js.getString("Code")) == 0) {

						// 保存用户名，密码,方便后边调用
						ApplicationData.getInstance().setUserName(username);
						ApplicationData.getInstance().setUserPassword(et_userConfirmPassword.getText().toString());
						ApplicationData.getInstance().setUserID(
								js.getString("Data"));
						MyPreference.getInstance(JddAlterPassActivity.this).setUserId(
								ApplicationData.getInstance().getUserID());
						
						
						//((JddMainActivity)getActivity()).refreshUserEvent();
//						EventManager.getInstance().onEvent(EventType.EV_BLL_lOGION_REFRESHUSEREVENT, null);
						EventManager.getInstance().onEvent(EventType.EV_BLL_UI_MAIN_LOT_REFRESH, null);
					} else {
						Toast.makeText(JddAlterPassActivity.this, js.getString("Data"),
								Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException ex) {
					// 异常处理代码
					Log.e("error", ex.toString());
				} finally {
					showdialog.closeDialog();
				}
			} else {
				Toast.makeText(JddAlterPassActivity.this,
						JddAlterPassActivity.this.getString(R.string.problem_01),
						Toast.LENGTH_LONG).show();
			}
			finish();
		}

		// 5.完成后操作
		protected void onCancelled() {
		}
	}
}
